<?php
namespace Admin\Controller;
use Admin\Controller\BaseController;

class CourseController extends BaseController {

	public function index() {
		$courses = D('Course')->relation('major')->select();
		$this->assign('courses', $courses);
		$this->display();
	}

	public function add() {
		$academies = M('Academy')->select();
		$academyId = (int)$academies[0]['id'];
		$majors = M('Major')->where(array('academy_id' => $academyId))->select();
		$this->assign('academies', $academies);
		$this->assign('majors', $majors);
		$this->display();
	}

	public function addPost() {
		if(!IS_POST) {
			$this->redirect('Course/index');
		}
		$course = D('Course');
		if(!$course->create()) {
			$this->error($course->getError(), U('Course/add'));
		}
		if(!$course->checkUnique($course->data())) {
			$this->error('课程已存在！', U('Course/add'));
		}
		if(!$course->add()) {
			$this->error('数据写入失败！', U('Course/add'));
		}
		$this->success('添加成功！', U('Course/index'), 0);
	}

	public function deletePost() {
		if(!IS_POST) {
			$this->redirect('Course/index');
		}
		$id = (int)I('post.id');
		$course = D('Course');
		if($course->hasChildObj($id)) {
			$this->error($course->getError());
		}
		if(M('Course')->where(array('id' => $id))->delete()) {
			$this->success('删除成功！', U('Course/index'), 0);
		} else {
			$this->error('删除失败！');
		}
	}

	public function modify() {
		$id = (int)I('id');
		$this->_detail($id);
		$this->display();
	}

	public function modifyPost() {
		if(!IS_POST) {
			$this->redirect('Course/index');
		}
		$id = (int)I('post.id');
		$course = D('Course');
		if(!$course->create()) {
			$this->error($course->getError(), U('Course/modify', array('id' => $id)));
		}
		if(!$course->checkUnique($course->data())) {
			$this->error('课程已存在！', U('Course/modify', array('id' => $id)));
		}
		$result = $course->save();
		if($result === false) {
			$this->error('数据更新失败！', U('Course/modify', array('id' => $id)));
		}
		$this->success('修改成功！', U('Course/index'), 0);
	}

	public function detail() {
		$id = (int)I('id');
		$this->_detail($id);
		$this->display();
	}

	protected function _detail($id) {
		$course = D('Course')->where(array('id' => $id))->relation('major')->find();
		$majorId = (int)$course['major']['id'];
		$academyId = (int)$course['major']['academy_id'];
		$majors = M('Major')->where(array('academy_id' => $academyId))->select();
		$academies = M('Academy')->select();
		$this->assign('course', $course);
		$this->assign('academy_id', $academyId);
		$this->assign('academies', $academies);
		$this->assign('major_id', $majorId);
		$this->assign('majors', $majors);
	}
	
}
